/* combo URL when method is GET
   arg data: obj
*/
function comboURL(url, data){
    var l = [];
    for (var arg in data){
        l.push([arg, data[arg]].join('='))
    }
    return [url, l.join('&')].join('?');
}

var translation_table = {
    '请填写机构的名称':'Please enter school\'s name',
    '请填写学生姓名':'Please enter student\'s name',
    '请填写班级名称':'Please enter class\'s name',
    '请填写姓名':'Please enter the name',
    '请填写正确的email':'Please enter the correct E-mail',
    '请填写电话号码': 'Please enter the phone',
    '请填写正确的电话号码': 'Please enter the correct phone number',
    '地址长度至少是{0}':'Address length is at least {0}',
    '地址长度不能超过{0}字符':'Address length should not exceed {0}',
    '请填写正确的代码，由字母和数字组成':'Please enter the correct code,consisting of letters and numbers',
    '请填写正确的密码，长度在3~32之间':'Please enter the correct password, the length is between 3~32',
    '请填写正确日期格式如：2011-01-11':'Please enter the correct date format such as: 2011-01-11',
    '请填写联系人姓名': 'Please enter the contact name',
    '请填写学校代码':'Please enter the school code',
    '请填写地址信息':'Please enter the address',
    '请填写密码':'Please enter the password',
    '请填写新密码':'Please enter the new password',
    '请填写原密码':'Please enter the old password',
    '请填写生日日期':'Please enter the birthday',
    '请填写家长姓名':'Please enter parent name',
    '验证码不能为空':'Verification code cannot be empty',
    '请填写家长email':'Please enter parent E-mail',
    '请填写用户名':'Please enter the username',
    '请填写钢琴ID':'Please enter the piano\'s ID',
    '请填写设备ID':'Please enter the device\'s ID',
    '请填写开展时间':'Please enter the begining time of exhibition',
    '请填写闭展时间':'Please enter the end time of exhibition',
    '请填写确认密码':'Please enter the password'
}

function translator(key){
    if(localStorage.lang == 'lang=en'){
        return translation_table[key] || key;
    }else{
        return key;
    }
}

function getPaginationInfo(){
    var data = {
        'page': parseInt($('.page option:selected').text()) || 1,
        'per_page': parseInt($('.per_page option:selected').text())
    };
    return data;
}

function pageChangeEvent(d){
    var data = d ? d : getPaginationInfo();
    var page = data['page'];

    if (parseInt(page) == 0) return;
    var total_count = parseInt($('#count').text());

    if ( (total_count!=0) && (parseInt(page)>parseInt($('#total_pages').text())) ) return;

    var url = window.location.pathname;


    if (url == "/school/students") {
        // add select stat and class id when on students page
        data['class'] = $('#courseTypeSelect').val();
        data['mc_stat'] = $('#typeselect').val();
        data['stat'] = $('#studentselect').val();
    }
    if (url == '/school/teachers') {
        // add select stat when on students page
        data['stat'] = $('#teacherselect').val();
    }
    if (url == '/school/classes'){
        data['course_type'] = $('#courseTypeSelect').val();
        data['stat'] = $('#classselect').val();
        data['type'] = $('#typeselect').val();
    }

    window.location.href = comboURL(url, data);
}

function bindPaginationEvents(){

    /* Pagination Events*/
    // change per_page
    $('.per_page').bind('change', function(){
        var data = getPaginationInfo();
        data['page'] = 1;
        pageChangeEvent(data);
    });

    // change page
    $('.page').bind('change', function(){
        pageChangeEvent();
    });

    // click next
    $('#next').bind('click', function(){
        var data = getPaginationInfo();
        data['page'] += 1;
        pageChangeEvent(data);
    });

    // click prev
    $('#prev').bind('click', function(){
        var data = getPaginationInfo();
        data['page'] -= 1;
        pageChangeEvent(data);
    });
}

function check_date(obj){
    var start_date = new Date(1900,01,01); 
    var date_arr = obj.val().split('-');
    var input_date = new Date(date_arr[0], date_arr[1], date_arr[2]);
    if(!input_date  || input_date < start_date){
        obj.val('1900-01-01');
    }
}

// init datetime picker
function init_datetimepicker(lang){
    var defaultLang = 'zh-CN';
    if(lang == 'lang=en'){
        defaultLang = 'en'
    }
    $('#day_of_birth').datetimepicker({
        format:'yyyy-mm-dd',
        autoclose:true,
        todayBtn:true,
        minView:2,
        endDate: new Date(),
        language: defaultLang
    }).on('hide', function(){
        check_date($(this));
    }).blur(function(){
        check_date($(this));
    });
}

// set the nav page highlight when click
function setActiveLi(){
    var lis=$('.nav.nav-pills.nav-stacked>li');
        // hlis=$('#navbar li');
    // var arr=[lis,hlis];
    var pathname=location.pathname.split('/')[1];
    var log_in = location.pathname.split('/')[2];
    var index=0;
		// for(var i=0;i<arr.length;i++){
		// 	arr[i].each(function(index,item){
  //               console.log(index);
		// 		$(item).bind('click',function(){
		// 			if(window.sessionStorage){
		// 				sessionStorage.setItem(pathname,index);
		// 			}
		// 		});
		// 	});
		// }
        lis.bind('click',function(){
            index=lis.index($(this));
            sessionStorage.setItem(pathname,index);
        });
		index=sessionStorage.getItem(pathname);
		
        if(pathname==='student' && !index){
            lis.eq(1).addClass('active');
        }
        else{
            lis.eq(index).addClass('active');
        }
		// hlis.eq(index).addClass('active');
		if(pathname=='manage' && location.pathname.indexOf('classrooms')>0){
				lis.eq(0).removeClass('active');
				// hlis.eq(0).removeClass('active');
				$('.nav.nav-pills.nav-stacked>li.classroom').addClass('active');
				$('#navbar li.classroom').addClass('active');
		}
}

/* validation configuration begin */
// Some global variable for form field validate

var nameRequireOnly = {
    name: {
        required: true
    }
};

var _FormValidateRuleMap = {

    'StudentInfoForm': nameRequireOnly,
    'teacherNewForm': nameRequireOnly,
    'teacherEditForm': nameRequireOnly,
    'StudentAccountForm': nameRequireOnly
}


var _FormValidateInfoMap = {
    'SchoolForm': {
        name: {
            required: translator('请填写机构的名称'),
            minlength: $.validator.format('机构名称长度至少是{0}'),
            maxlength: $.validator.format('机构名称长度不能超过{0}字符')
        }        
    },
    'StudentInfoForm': {
        name: {
            required: translator('请填写学生姓名')
        }
    },
    'MusicClassForm': {
        name: {
            required: translator('请填写班级名称'),
            minlength: $.validator.format('班级名称长度至少是{0}'),
            maxlength: $.validator.format('班级名称不能超过{0}字符')
        }
    }    
}

var commonRegx = {
    phone: /^(\d{3,4}-?)?\d{7,8}$/,
    school_code: /^[A-Za-z0-9]+$/,
    password: /^\S.{1,32}\S$/,
    date: /^\d{4}-[0-1][0-9]-[0-3][0-9]$/,
	username: /^[a-zA-z]\w{2,15}$/,
    name: /^[\u4e00-\u9fa5a-zA-Z]{2,15}$/
}

var commonRules = {
    name: {
        required: true
	},
    email: {
        //required: true,
        email: true
    },
    phone: {
        required: true,
        telephone: true
    },
    contact_name: {
        required: true,
        _name: true
    },
    code: {
        required: true,
        school_code: true
    },
    address: {
        required: true,
        minlength: 2,
        maxlength: 200
    }, 
    password: {
        required: true,
        pwd: true            
    },
    pwd: {
        required: true,
        pwd: true
    },
    new_pwd: {
        required: true,
        pwd: true
    },
    old_pwd: {
        required: true,
        pwd: true
    },
    confirm_pwd: {
        required: true,
        pwd: true
    },
    day_of_birth: {
        required: true,
        birth_date: true
    },
    parent_name: {
        required: true,
        _name: true
    },
    parent_phone: {
        required: true,
        telephone: true
    },
    parent_email: {
        required: true,
        email: true
    },
    username: {
        required: true,
        username: true
    },
    piano_id: {
        required: true
    },
    tablet_id: {
        required: true
    }     
};

var commonMessage = {
    name: {
        required: translator('请填写姓名')
    },
    email: {
        //required: '请填写email',
        email: translator('请填写正确的email')
    }, 
    phone: {
        required: translator('请填写电话号码')
    },
    contact_name: {
        required: translator('请填写联系人姓名')
    },
    code: {
        required: translator('请填写学校代码')
    },
    address: {
        required: translator('请填写地址信息'),
        minlength: $.validator.format(translator('地址长度至少是{0}')),
        maxlength: $.validator.format(translator('地址长度不能超过{0}字符'))
    },
    password: {
        required: translator('请填写密码')
    },
    pwd: {
        required: translator('请填写密码')
    },
    new_pwd: {
        required: translator('请填写新密码')
    },
    old_pwd: {
        required: translator('请填写原密码')
    },
    confirm_pwd: {
        required: translator('请填写确认密码')
    },
    day_of_birth: {
        required: translator('请填写生日日期')
    },
    parent_name: {
        required: translator('请填写家长姓名')
    },
    parent_phone: {
        required: ''
    },
    verify: {
        required: translator('验证码不能为空')
    },
    parent_email: {
        required: translator('请填写家长email'),
        email: translator('请填写正确的email')
    },
    username: {
        required: translator('请填写用户名')
    },
    piano_id: {
        required: translator('请填写钢琴ID')
    },
    tablet_id: {
        required: translator('请填写设备ID')
    },
    start_at: {
        required: translator('请填写开展时间')
    },
    end_at: {
        required: translator('请填写闭展时间')
    }           
       
};

/*
$.validator.addMethod("_name", function(value, element){
    return this.optional(element) || commonRegx.name.test(value);
}, '只能包含中英文字符，长度在2~15之间');
*/

$.validator.addMethod("telephone", function(value, element){
    return this.optional(element) || commonRegx.phone.test(value);
}, translator('请填写正确的电话号码'));

$.validator.addMethod("school_code", function(value, element){
    return this.optional(element) || commonRegx.school_code.test(value);
}, translator('请填写正确的代码，由字母和数字组成'));

$.validator.addMethod("pwd", function(value, element){
    return this.optional(element) || commonRegx.password.test(value);
}, translator('请填写正确的密码，长度在3~32之间'));

$.validator.addMethod("birth_date", function(value, element){
    return this.optional(element) || commonRegx.date.test(value);
}, translator('请填写正确日期格式如：2011-01-11'));

/*$.validator.addMethod("username", function(value, element){
    return this.optional(element) || commonRegx.username.test(value);
}, '请填写正确的用户名格式');
*/
/* validation configuration end */


// init form fields validations
// The form validated must be the only one
function initFormValidations(){
    var $forms = $('form.form-horizontal');
    if ($forms.length > 1){
        throw "muti forms have been selected";
    };
    if ($forms.length == 0){
        return;
    };

    var form_type = $forms[0].id;

    var specialMessage = _FormValidateInfoMap[form_type];
    var specialRule = _FormValidateRuleMap[form_type];

    var rules = $.extend(commonRules, specialRule);
    var messages = $.extend(commonMessage, specialMessage);

    $forms.validate({
        rules: rules,
        messages: messages
    });
}

$(function(){
    setActiveLi();
    bindPaginationEvents();
    initFormValidations();

    // init table locale to zh-CN.

    init_datetimepicker(localStorage.lang);

    // change class on student page
    $('#music_class').bind('change', function(){
        var data = getPaginationInfo();
        data['page'] = 1;
        pageChangeEvent(data);
    });

    // check all click
    $('thead :checkbox,.m-ul-table .header :checkbox').click(function(){
        var is_checked = $(this).prop('checked');
        if (is_checked){
            var checkbox_list = $('tbody :checkbox,.cell-checkbox :checkbox')
            for (var i = 0; i < checkbox_list.length; i ++) {
                if (! checkbox_list[i].disabled) {
                    checkbox_list[i].checked = true
                }
            }
            $('.m-fixed-table-top').find('.del,.move').removeClass('disabled');
        }
        else {
            var checkbox_list = $('tbody :checkbox,.cell-checkbox :checkbox')
            for (var i = 0; i < checkbox_list.length; i ++) {
                if (! checkbox_list[i].disabled) {
                    checkbox_list[i].checked = false
                }
            }
            $('.m-fixed-table-top').find('.del,.move').addClass('disabled');
        }
    });

    $('tbody :checkbox,.m-ul-table :checkbox').click(function(){
        var checked=$('tbody :checkbox:checked,.m-ul-table :checkbox:checked');
        if(checked.length>0){
           $('.m-fixed-table-top').find('.del,.move').removeClass('disabled'); 
        }
        else{
           $('.m-fixed-table-top').find('.del,.move').addClass('disabled'); 
        }
    });

    $('.alert').animate({top:'72px'},200);
    setTimeout(function(){
        $('.alert').animate({top:0},300);
    },4000);
});

